﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WH.Contracts.Dtos;
using WH.Contracts.Systems.KeyValues;
using WH.Services.IServices.ISystem;
using Rw.Core.Common;
using Rw.Core.Common.Paging;
using WH.Common.DbConfig;
using WH.Common.Helper;
using WH.Common.Paging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WH.WebApi.Controllers.Systems
{
    /// <summary>
    /// code类型：People|绑定者类型-人员，Thing|绑定者类型-资产，Envir|绑定者类型-环境，DeviceType|设备类型
    /// </summary>
    [Authorize, Route("key-values"), ApiController]
    public class KeyValuesController : BaseController
    {
        private readonly IKeyValueService _keyValueService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyValueService"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public KeyValuesController(IKeyValueService keyValueService)
        {
            _keyValueService = keyValueService ?? throw new ArgumentNullException(nameof(keyValueService));
        }

        /// <summary>
        /// 添加类型
        /// </summary>
        /// <param name="code">类型编号</param>
        /// <param name="input">名称</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task<ResultResponse> PostBinderTypeAsync([FromBody] KeyValueInputDto input)
        {
            var inputData = input.TrimAll();

            var res = await _keyValueService.CreateAsync(inputData);
            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 编辑类型
        /// </summary>
        /// <param name="id">类型主键</param>
        /// <param name="input">名称</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResultResponse> PutBinderTypeAsync(string id, [FromBody] KeyValueInputDto input)
        {
            var inputData = input.TrimAll();

            if (id == input.ParentId)
            {
                return Error("不能将自身作为父级节点，请检查");
            }

            var res = await _keyValueService.UpdateAsync(id, inputData);
            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="code">类型编号</param>
        /// <param name="id">类型主键</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResultResponse> DeleteBinderTypeAsync(string id)
        {
            var res = await _keyValueService.RemoveAsync(k => k.Id == id && k.IsDeletable);
            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 字典列表数据
        /// </summary>
        /// <param name="code">类型编号</param>
        /// <returns></returns>
        [HttpGet("{idOrCode}")]
        public async Task<ResultResponse<KeyValueOutputDto>> GetBinderTypesAsync(string idOrCode)
        {
            var keyValue = await _keyValueService.GetKeyValByCodeAsync(idOrCode.Trim());
            if (keyValue == null)
            {
                return new ResultResponse<KeyValueOutputDto>
                {
                    IsSucceed = false,
                    Msg = "父级类型不正确"
                };
            }
            return Success(keyValue);
        }

        /// <summary>
        ///字典列表数据
        /// </summary>
        /// <param name="enCode"></param>
        /// <returns></returns>
        [HttpGet("Select/{enCode}")]
        public async Task<ResultResponse<List<KeyValuesListDto>>> GetKeyValueJson(string enCode = "")
        {
            if (string.IsNullOrWhiteSpace(enCode.Trim()))
            {
                return Error<List<KeyValuesListDto>>("参数enCode不可为空");
            }

            var item = await _keyValueService.GetKeyValueChildByCodeListAsync(enCode.Trim());

            var data = (from a in item
                        select new KeyValuesListDto
                        {
                            Id = a.Id,
                            ParentId = a.ParentId,
                            TypeCode = a.Code,
                            TypeIconUrl = a.IconUrl,
                            TypeName = a.Name,
                            IsEnable = a.IsEnable,
                        }).ToList();

            return Success(data);
        }


        /// <summary>
        ///字典列表数据(按配置取)
        /// </summary>
        /// <param name="link"></param>
        /// <returns></returns>
        [HttpGet("SelectLink")]
        public async Task<ResultResponse<List<KeyValuesListDto>>> GetKeyValueJsonByLink([FromQuery] string? link)
        {
            if (string.IsNullOrWhiteSpace(link))
            {
                return Error<List<KeyValuesListDto>>("参数enCode不可为空");
            }

            var config = new DatabaseConfigurationProvider()[link];

            if (config is null || string.IsNullOrWhiteSpace(config.Value))
            {
                return Success(new List<KeyValuesListDto>());
            }

            var codes = config.Value.Split(",");

            var item = await _keyValueService.FindAllAsync(x => x.IsEnable && codes.Contains(x.Code));

            var data = (from a in item
                        select new KeyValuesListDto
                        {
                            Id = a.Id,
                            ParentId = a.ParentId,
                            TypeCode = a.Code,
                            TypeIconUrl = a.IconUrl,
                            TypeName = a.Name,
                            IsEnable = a.IsEnable,
                        }).ToList();

            return Success(data);
        }


        ///// <summary>
        ///// 获取树菜单
        ///// </summary>
        ///// <param name="organizationId"></param>
        ///// <param name="code"></param>
        ///// <returns></returns>
        //[HttpGet("SelectTree")]
        //public async Task<ResultResponse<KeyValueTreeOutputDto>> SelectTreeByCode(string code)
        //{
        //    var result = new ResultResponse<KeyValueTreeOutputDto>();

        //    try
        //    {
        //        if (string.IsNullOrWhiteSpace(code))
        //        {
        //            result.IsSucceed = false;
        //            result.Msg = "菜单code不能为空";
        //            return result;
        //        }

        //        var data = await _keyValueService.FindTree(code);

        //        result.IsSucceed = true;
        //        result.Msg = "查询成功";
        //        result.Data = data;
        //    }
        //    catch (Exception ex)
        //    {
        //        result.IsSucceed = false;
        //        result.Msg = ex.Message;
        //    }

        //    return result;
        //}

        /// <summary>
        /// 获取树菜单
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpGet("Trees/{parentId}")]
        public async Task<ResultResponse<IList<KeyValueTreeOutputDto>>> SelectTreeByParentId(string? parentId)
        {
            parentId = string.IsNullOrEmpty(parentId) ? Request.Query["parentId"] : parentId;

            if (string.IsNullOrWhiteSpace(parentId))
            {
                return Error<IList<KeyValueTreeOutputDto>>("parentId不能为空");
            }

            var data = await _keyValueService.FindTreeByParentId(parentId);

            return Success(data);
        }

        /// <summary>
        /// 获取树菜单
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("Trees/AllByParentCode")]
        public async Task<ResultResponse<IList<KeyValueTreeOutputDto>>> SelectTreeByParentCode([FromQuery] string? parentCode)
        {
            if (string.IsNullOrWhiteSpace(parentCode))
            {
                return Error<IList<KeyValueTreeOutputDto>>("parentCode不能为空");
            }

            var data = await _keyValueService.FindTreeAllByParentCode(parentCode);

            return Success(data);
        }

        /// <summary>
        /// 获取树菜单
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("EnableTrees")]
        public async Task<ResultResponse<IList<KeyValueTreeOutputDto>>> SelectEnableTreeByParentCode([FromQuery] string? parentCode)
        {
            if (string.IsNullOrWhiteSpace(parentCode))
            {
                return Error<IList<KeyValueTreeOutputDto>>("parentCode不能为空");
            }
            var data = await _keyValueService.FindTree(parentCode);

            return Success(data?.Children ?? new List<KeyValueTreeOutputDto>());
        }


        /// <summary>
        /// 获取树菜单
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        [HttpGet("EnableTreesHasSelf")]
        public async Task<ResultResponse<IList<KeyValueTreeOutputDto>>> SelectEnableTreesHasSelfByParentCode([FromQuery] string? parentCode)
        {
            if (string.IsNullOrWhiteSpace(parentCode))
            {
                return Error<IList<KeyValueTreeOutputDto>>("parentCode不能为空");
            }
            var data = await _keyValueService.FindTree(parentCode);

            IList<KeyValueTreeOutputDto> res = new List<KeyValueTreeOutputDto>() { data };

            return Success(res);
        }


        ///// <summary>
        ///// 获取树菜单
        ///// </summary>
        ///// <param name="parentId"></param>
        ///// <returns></returns>
        //[HttpGet("Trees/All/{parentId}")]
        //public async Task<ResultResponse<IList<KeyValueTreeOutputDto>>> SelectTreeAllByParentId(string? parentId)
        //{

        //    if (string.IsNullOrWhiteSpace(parentId))
        //    {
        //        return Error<IList<KeyValueTreeOutputDto>>("parentId不能为空");
        //    }

        //    var data = await _keyValueService.FindTreeAllByParentId(parentId);

        //    return Success(data);
        //}


        /// <summary>
        /// 获取字典值列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="pager"></param>
        /// <param name="keywords"></param>
        /// <returns></returns>
        [HttpGet("Page/{parentId}")]
        public async Task<ResultResponse<IPagedList<KeyValueTreeOutputDto>>> GetTreeValues(string? parentId, [FromQuery] PageParam pager, [FromQuery] string? keywords)
        {
            parentId = string.IsNullOrEmpty(parentId) ? Request.Query["parentId"] : parentId;

            if (string.IsNullOrWhiteSpace(parentId))
            {
                return Error<IPagedList<KeyValueTreeOutputDto>>("parentId不能为空");
            }

            var data = await _keyValueService.FindTreeByParentId(parentId);

            if (!string.IsNullOrWhiteSpace(keywords))
            {
                data = data.Where(x => x.Name.Contains(keywords) || x.Code.Contains(keywords)).ToList();
            }

            return Success(data.ToPaged(pager));
        }
    }
}